<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends AIA_Controller {

    function __construct() {
        parent::__construct();
        // $this->_check_user();
    }

    public function index() {
        // $id = $this->input->get('haha', true);
        // $this->load->database();
        // $this->load->model('Aia_model');
        // $row = $this->Aia_model->get_share_info($id);
    	$this->load_resource();
        // $this->load->view('public/header', $row);
    	$this->load->view('public/header');
    	$this->load->view('index');
    	$this->load->view('public/footer');
    }

    protected function _get_img_from_wx($media_id) {
        $dir = 'upload/';
        $access_token = $this->_get_wx_access_token();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$media_id";
        // $content = $this->_curl_request('get', $url, $data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $content = curl_exec($ch);
        curl_close($ch);
        $filename = $dir . $this->_generate_random_str() . '.jpg';
        $file = fopen($filename, 'w');
        if (false !== $file) {
            fwrite($file, $content);
            fclose($file);
        }
        return $filename;
        // $result = array(
        //     'code' => 1
        // );
        // $this->output->set_content_type('application/json')->set_output(json_encode($result));
    }

    protected function _commit($request) {
        $words = $request['words'];
        $media_id = $request['media_id'];
        $result = array(
            'code' => 0
        );
        if ($words === false) {
            $result['msg'] = 'Please fill in words';
        } elseif ($media_id === false) {
            $result['msg'] = 'Please upload image file';
        } else {
            $data = array(
                'words' => htmlspecialchars($words),
                'img' => $this->_get_img_from_wx($media_id)
            );
            $this->load->database();
            $this->load->model('Aia_model');
            $id = $this->Aia_model->insert_share($data);
            $result['code'] = 1;
            $result['redirect'] = base_url('share?haha=' . $id);
        }
        $this->output->set_content_type('application/json')->set_output(json_encode($result));
    }

}

/* End of file index.php */
/* Location: ./application/controllers/index.php */